package com.my.lab.activity;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

import com.my.lab.R;
import com.my.lab.net.NetMonitorThread;
import com.my.lab.net.TcpMonitorSocketThread;
import com.my.lab.util.ConfigConstant;
import com.my.lab.util.InputStreamUtils;

public class UdpActivity extends Activity {

    DatagramSocket ds = null;

    DatagramSocket sds = null;

    String data1 = null;

    byte[] buf = new byte[1024];

    DatagramPacket receiveDp = new DatagramPacket(buf, 1024);

    boolean flag = true;

    TextView tv1;

    NetMonitorThread monitorThread;

    TcpMonitorSocketThread tcpThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.udp_layout);
        tv1 = (TextView) findViewById(R.id.tv1);
        initMonitor();

        /*
         * try { ds = new DatagramSocket(ConfigConstant.UDP_BOADCASTPORT); sds =
         * new DatagramSocket(ConfigConstant.UDP_SEND); new Thread(new
         * Runnable() {
         * 
         * @Override public void run() { ServerSocket ss = null; InputStream is
         * = null; OutputStream os = null; FileOutputStream fos = null; Socket
         * connectSocket = null; byte headtype = 0; try { ss = new
         * ServerSocket(ConfigConstant.TCP_CONNECTPORT); connectSocket =
         * ss.accept(); // accept阻塞直到被连接 Log.d("",
         * "ConnectThread Connected...");
         * 
         * is = connectSocket.getInputStream(); // File img = new
         * File(ConfigConstant._apkfile); // if(img.exists()) { // img.delete();
         * // } // fos = new FileOutputStream(img); JSONObject json = new
         * JSONObject(InputStreamUtils.InputStreamTOString(is, "gbk")); // byte
         * buffer[] = new byte[ConfigConstant.WIFI_BUFFER_LENGTH]; // int left =
         * 0; // while ((left = is.read(buffer) )!= -1) { // fos.write(buffer,
         * 0, left); // fos.flush(); // } ss.close(); connectSocket.close();
         * is.close(); // os.close(); fos.close(); } catch (Exception e) {
         * e.printStackTrace(); } finally { } } }).start();
         * 
         * new Thread(new Runnable() {
         * 
         * @Override public void run() { while (flag) { try { runOnUiThread(new
         * Runnable() { public void run() { tv1.setText("监听广播,端口" +
         * ConfigConstant.UDP_BOADCASTPORT); } }); ds.receive(receiveDp);
         * Log.d("", "hostName:" + receiveDp.getAddress().getHostName() +
         * ",hotaddress:" + receiveDp.getAddress().getHostAddress()); } catch
         * (IOException e) { e.printStackTrace(); } if (receiveDp.getLength() !=
         * 0) { flag = false; runOnUiThread(new Runnable() { public void run() {
         * String str = ""; try { str = new String(buf, 0,
         * receiveDp.getLength(), "gbk"); } catch (UnsupportedEncodingException
         * e) { // TODO Auto-generated catch block e.printStackTrace(); }
         * 
         * tv1.setText("收到广播,端口" + ConfigConstant.UDP_BOADCASTPORT+",内容:"+str);
         * } }); String code = ""; try { code = new String(buf, "gbk"); String
         * sendCode = "回复服务端数据:" + code; byte[] buf = sendCode.getBytes("gbk");
         * DatagramPacket sendDp = new DatagramPacket(buf, 0, buf.length,
         * receiveDp.getAddress(), ConfigConstant.UDP_SEND); sds.send(sendDp); }
         * catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch
         * (IOException e) { e.printStackTrace(); } data1 = data1 + "\n" + code;
         * runOnUiThread(new Runnable() { public void run() {
         * tv1.setText(data1); } }); } } } }).start();
         * 
         * } catch (SocketException e) { e.printStackTrace(); } catch
         * (IOException e) { e.printStackTrace(); }
         */

    }

    /**
     * 初始化监听线程
     */
    private void initMonitor() {
        monitorThread = NetMonitorThread.newInstance();
        monitorThread.connectSocket(mHandler);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case 0:
                InetAddress address = (InetAddress) msg.obj;
                if (address != null) {
                    tcpThread = new TcpMonitorSocketThread(address.getHostName());
                    tcpThread.beginMonitorTcp(this);
                }
                break;
            case 1:
                JSONObject json = (JSONObject) msg.obj;
                Log.d("", "接收到json数据:" + json.toString());
                break;
            }

        }
    };

}
